
//搜索条件
var empName = "";
var leaveDate = "";
var current = 1;
var length = 10;
var leaveBillTotal = 0;
var currentPage = 1;
var totalPage = 0;
var count = 0;

function updateLeaveBill(id) {
	$.ajax({
		url : "http://localhost:8888/simple_activiti/leave/select_leave.do",
		dataType : "json",
		type : "post",
		data : "id=" + id,
		success : function(result) {
			if (result.data[0].hasError) {
				window.wxc.xcConfirm(data[0].errorMsg,
						window.wxc.xcConfirm.typeEnum.error);
			} else {
				$("#updateLeaveBillId").val(id);
				$("#updateLeaveBillDays").val(result.data[0].days);
				$("#updateLeaveBillContent").val(result.data[0].content);
				$("#updateLevaveBillRemark").val(result.data[0].remark);
				$("#updateModal").modal('show');
			}
		},
		error : function(data) {
			var txt = $.i18n.prop("leave_request_fail");
			window.wxc.xcConfirm(txt, window.wxc.xcConfirm.typeEnum.error);
		}
	});

}

$("#submitUpdate")
		.click(
				function() {
					$
							.ajax({
								url : "http://localhost:8888/simple_activiti/leave/update_leave.do",
								dataType : "json",
								type : "post",
								data : $("#addOrUpdateForm").serialize(),
								success : function(data) {
									if (data.hasError) {
										window.wxc
												.xcConfirm(
														data.errorMsg,
														window.wxc.xcConfirm.typeEnum.error);
									} else {
										var txt = $.i18n
												.prop("leave_tip_update_success");
										window.wxc
												.xcConfirm(
														txt,
														window.wxc.xcConfirm.typeEnum.success,
														{
															onOk : function() {
																window.parent
																		.$(
																				"#updateModal")
																		.modal(
																				'hide');
																fillTableData();
															}
														});
									}
								},
								error : function(data) {
									var txt = $.i18n.prop("leave_request_fail");
									window.wxc
											.xcConfirm(
													txt,
													window.wxc.xcConfirm.typeEnum.error);
								}
							});
				});
$("#submitAdd")
		.click(
				function() {
					$
							.ajax({
								url : "http://localhost:8888/simple_activiti/leave/add_leave.do",
								dataType : "json",
								type : "post",
								data : $("#addForm").serialize(),
								success : function(data) {
									if (data.hasError) {
										window.wxc
												.xcConfirm(
														data.errorMsg,
														window.wxc.xcConfirm.typeEnum.error);
									} else {
										var txt =  $.i18n.prop("leave_tip_add_success");
										window.wxc
												.xcConfirm(
														txt,
														window.wxc.xcConfirm.typeEnum.success,
														{
															onOk : function() {
																$(
																		"#addLeaveModal")
																		.modal(
																				'hide');
																fillTableData();
															}
														});
									}
								},
								error : function(data) {
									var txt = $.i18n.prop("leave_request_fail");
									window.wxc
											.xcConfirm(
													txt,
													window.wxc.xcConfirm.typeEnum.error);
								}
							});

				});
function search() {
	empName = $("#leaveName").val();
	leaveDate = $("#leaveTime").val();

	fillTableData();
}

function deleteLeaveBill(id) {
	var txt =  $.i18n.prop("leave_del_confirm");
	window.wxc
			.xcConfirm(
					txt,
					window.wxc.xcConfirm.typeEnum.warning,
					{
						onOk : function() {
							$
									.ajax({
										url : "http://localhost:8888/simple_activiti/leave/delete_leave.do",
										dataType : "text",
										data : "id=" + id,
										success : function() {
											var txt = $.i18n.prop("leave_tip_delete_success");
											window.wxc
													.xcConfirm(
															txt,
															window.wxc.xcConfirm.typeEnum.success,
															{
																onOk : function() {
																	fillTableData();
																	// 数量变了，重新的到数量初始化分页
																	getTotalCount();
																}
															});
										},
										error : function() {
											var txt = $.i18n
													.prop("leave_request_fail");
											window.wxc
													.xcConfirm(
															txt,
															window.wxc.xcConfirm.typeEnum.error);
										}
									});
						}
					});
}
function startProcess(id) {
	$
			.ajax({
				url : "http://localhost:8888/simple_activiti/workflow/start_process.do",
				dataType : "json",
				data : "id=" + id,
				success : function(data) {

					if (data.hasError) {
						window.wxc.xcConfirm(data.errorMsg,
								window.wxc.xcConfirm.typeEnum.error);
					} else {
						window.location.href = "http://localhost:8888/simple_activiti/workflow/personal_task.do";
					}
				},
				error : function(data) {
					var txt = $.i18n.prop("leave_request_fail");
					window.wxc.xcConfirm(data.responseText,
							window.wxc.xcConfirm.typeEnum.error);
				}
			});
}

$(function() {
	// 请假时间搜索
	$('#leaveTime').datepicker({
		language : 'zh-CN',
		pickTime : false,
		todayBtn : false,
		autoclose : true,
		minView : '4',
		forceParse : false,
		format : "yyyy-mm-dd",
		top : "47px"
	});
	// 表格数据填充
	fillTableData();
	// 得到总记录数，成功后对分页初始化
	getTotalCount();

});
/**
 * 填充表格
 */
function fillTableData() {
	$
			.ajax({
				url : "http://localhost:8888/simple_activiti/leave/leave_list_page.do",
				dataType : "json",
				type : "post",
				data : {
					empName : empName,
					leaveDate : leaveDate,
					current : current,
					length : length
				},
				success : function(result) {
					if (result.hasError) {
						window.wxc.xcConfirm(result.errorMsg,
								window.wxc.xcConfirm.typeEnum.error);
					} else {
						// 设置数据
						var data = result.data;
						var htmlData = "";
						for (var i = 0; i < data.length; i++) {
							htmlData += "<tr><td>" + data[i].id + "</td>";
							htmlData += "<td>" + data[i].realName + "</td>";
							htmlData += "<td>" + data[i].days + "</td>";
							htmlData += "<td>" + data[i].content + "</td>";
							htmlData += "<td>" + data[i].remark + "</td>";
							htmlData += "<td>" + data[i].leaveDate + "</td>";
							var status = "";
							var doCase = "";
							
							if (data[i].state == 0) {
								status = $.i18n.prop("leave_status_new");
								doCase = "<a href='#' onclick='startProcess("
										+ data[i].id + ")'>"+$.i18n.prop("leave_apply")+"</a>";
							} else if (data[i].state == 1) {
								status = $.i18n.prop("leave_status_approve");
								doCase = "<a href='http://localhost:8888/simple_activiti/workflow/view_his_comm.do?id="
										+ data[i].id + "'>"+$.i18n.prop("leave_audit_record")+"</a>";
							} else if (data[i].state == 2) {
								status = $.i18n.prop("leave_status_success");
								doCase = "<a href='http://localhost:8888/simple_activiti/workflow/view_his_comm.do?id="
										+ data[i].id + "'>"+$.i18n.prop("leave_audit_record")+"</a>";
							}
							htmlData += "<td>" + status + "</td>";
							
							var deleteHtml="<a href='javascript:void(0);' onclick='updateLeaveBill("
									+ data[i].id
									+ ")'>"
									+ $.i18n.prop("leave_btn_update");
							+"&nbsp;&nbsp;</a>";
							
							var updateHtml="<a href='javascript:void(0)'	onclick='deleteLeaveBill("
									+ data[i].id
									+ ")'>"
									+ $.i18n.prop("leave_btn_delete")
									+ "&nbsp;&nbsp;</a>";
							
							htmlData += "<td>" +updateHtml+deleteHtml+"&nbsp;&nbsp;"+doCase + "</td>";
							
							htmlData += "</tr>";
						}
						$("#leaveBillBody").html(htmlData);

						initTableCheckbox();
					}
				},
				error : function(result) {
					var txt = $.i18n.prop("leave_request_fail");
					window.wxc.xcConfirm(txt,
							window.wxc.xcConfirm.typeEnum.error);
				}
			});
}
/**
 * 得到总计录数
 */
function getTotalCount() {
	$
			.ajax({
				url : "http://localhost:8888/simple_activiti/leave/leave_list_page_count.do",
				dataType : "json",
				data : {
					empName : empName,
					leaveDate : leaveDate
				},
				success : function(data) {
					leaveBillTotal = data.count;
					initPagaData();
				},
				error : function(data) {
					var txt = $.i18n.prop("leave_request_fail");
					window.wxc.xcConfirm(txt,
							window.wxc.xcConfirm.typeEnum.error);
				}
			});
}
/**
 * 初始化分页
 */
function initPagaData() {

	var v_numberOfPages = 0;

	/*
	 * Math.ceil(count / pagesize); //向上整除 4/3=2; Math.floor(count / pagesize);
	 * //向下整除 4/3=1;
	 */
	if (leaveBillTotal % 10 == 0) {
		totalPage = leaveBillTotal / 10;
	} else {
		totalPage = Math.floor(leaveBillTotal / 10) + 1;
	}
	if (totalPage < 5) {
		v_numberOfPages = totalPage;
	} else {
		v_numberOfPages = 5;
	}

	// 填充分页栏
	var element = $('#leavePage');// 获得数据装配的位置
	// 初始化所需数据
	var options = {
		bootstrapMajorVersion : 3,// 版本号。3代表的是第三版本
		currentPage : 1, // 当前页数
		numberOfPages : v_numberOfPages, // 显示页码数标个数
		totalPages : totalPage, // 总共的数据所需要的总页数
		itemTexts : function(type, page, current) {
			// 图标的更改显示可以在这里修改。
			switch (type) {
			case "first":
				return "<<";
			case "prev":
				return "<";
			case "next":
				return ">";
			case "last":
				return ">>";
			case "page":
				return page;
			}
		},
		tooltipTitles : function(type, page, current) {
			// 如果想要去掉页码数字上面的预览功能，则在此操作。例如：可以直接return。
			switch (type) {
			case "first":
				return "Go to first page";
			case "prev":
				return "Go to previous page";
			case "next":
				return "Go to next page";
			case "last":
				return "Go to last page";
			case "page":
				return (page === current) ? "Current page is " + page
						: "Go to page " + page;
			}
		},
		onPageClicked : function(e, originalEvent, type, page) {
			// 单击当前页码触发的事件。若需要与后台发生交互事件可在此通过ajax操作。page为目标页数。
			// console.log("e="+e);
			// console.log("originalEvent="+originalEvent);
			// console.log("type="+type);
			// console.log("page="+page);
			current = page;
			// 填充表格数据
			fillTableData();

		}
	};
	element.bootstrapPaginator(options); // 进行初始化
}

/**
 * 支持键盘左右键上下分页
 */
$("body").keydown(function(event) {
	if (event.keyCode == 37 && current != undefined)
		if (current > 1) {
			current = current - 1;
			// 填充表格数据
			fillTableData();
		}

	if (event.keyCode == 39 && current != undefined)
		if (current < totalPage) {
			current = current + 1;
			// 填充表格数据
			fillTableData();
		}
});

/**
 * http://blog.csdn.net/shangmingchao/article/details/49761315
 * 这个地址的复选框案例是可以的由于我这里用的是动态生成表格所以要稍作修改 初始化表格的checkbox
 */
function initTableCheckbox() {
	// 每次添加的时候要将原来的复选状态改为false一面影响
	$("#checkAll").prop("checked", false);
	var $thr = $('#leaveBillTable table thead tr');
	var $checkAllTh = $('<th><input type="checkbox" id="checkAll" name="checkAll" /></th>');
	/* 将全选/反选复选框添加到表头最前，即增加一列 */
	if (count == 0) {
		$thr.prepend($checkAllTh);
		count = 1;
	}
	/* “全选/反选”复选框 */
	var $checkAll = $thr.find('input');
	$checkAll.click(function(event) {
		/* 将所有行的选中状态设成全选框的选中状态 */
		$tbr.find('input').prop('checked', $(this).prop('checked'));
		/* 并调整所有选中行的CSS样式 */
		if ($(this).prop('checked')) {
			$tbr.find('input').parent().parent().addClass('warning');
		} else {
			$tbr.find('input').parent().parent().removeClass('warning');
		}
		/* 阻止向上冒泡，以防再次触发点击操作 */
		event.stopPropagation();
	});
	/* 点击全选框所在单元格时也触发全选框的点击操作 */
	$checkAllTh.click(function() {
		$(this).find('input').click();
	});
	var $tbr = $('table tbody tr');
	var $checkItemTd = $('<td><input type="checkbox" name="checkItem" /></td>');
	/* 每一行都在最前面插入一个选中复选框的单元格 */
	$tbr.prepend($checkItemTd);
	/* 点击每一行的选中复选框时 */
	$tbr.find('input').click(
			function(event) {
				/* 调整选中行的CSS样式 */
				$(this).parent().parent().toggleClass('warning');
				/* 如果已经被选中行的行数等于表格的数据行数，将全选框设为选中状态，否则设为未选中状态 */
				$checkAll.prop('checked',
						$tbr.find('input:checked').length == $tbr.length ? true
								: false);
				/* 阻止向上冒泡，以防再次触发点击操作 */
				event.stopPropagation();
			});
	/* 点击每一行时也触发该行的选中操作 */
	$tbr.click(function() {
		$(this).find('input').click();
	});
}
/**
 * 批量删除
 */
function batchDelete() {
	var ids = "";
	var $check = $('#leaveBillTable table tbody tr input:checked');
	$check.each(function(index, item) {
		ids += $(this).parent().next().text() + ",";
	});

	if (ids != "") {
		var txt = $.i18n.prop("leave_oper_batch_del_confirm");
		window.wxc
				.xcConfirm(
						txt,
						window.wxc.xcConfirm.typeEnum.warning,
						{
							onOk : function() {
								$
										.ajax({
											url : "http://localhost:8888/simple_activiti/leave/batch_delete_leave.do",
											dataType : "text",
											data : "ids=" + ids,
											success : function() {
												var txt = $.i18n.prop("leave_batch_del_success");
												window.wxc
														.xcConfirm(
																txt,
																window.wxc.xcConfirm.typeEnum.success,
																{
																	onOk : function() {
																		fillTableData();
																		// 数量变了，重新的到数量初始化分页
																		getTotalCount();
																	}
																});
											},
											error : function() {
												var txt = $.i18n
														.prop("leave_request_fail");
												window.wxc
														.xcConfirm(
																txt,
																window.wxc.xcConfirm.typeEnum.error);
											}
										});
							}
						});
	} else {
		var txt =$.i18n.prop("leave_batch_delete_tip");
		window.wxc.xcConfirm(txt, window.wxc.xcConfirm.typeEnum.warning);
	}
}
var batchCurr = 1;
var idsStr = "";
var idsInt;
var batchTotal;

function batchUpdate() {
	// 添加校验，没选数据不能进来

	// 初始化数据，免得多次操作数据相互影响
	batchCurr = 1;
	idsStr = "";
	batchTotal = 0;
	idsInt = new Array();

	var $check = $('#leaveBillTable table tbody tr input:checked');
	var firstId = $check.eq(0).parent().next().text();
	$check.each(function(index, item) {
		idsStr += $(this).parent().next().text() + ",";
	});

	idsStr = idsStr.substring(0, idsStr.length - 1);
	idsInt = idsStr.split(",");
	batchTotal = idsInt.length;

	$.ajax({
		url : "http://localhost:8888/simple_activiti/leave/select_leave.do",
		dataType : "json",
		data : "id=" + firstId,
		type : "post",
		success : function(result) {
			if (result.hasError) {
				window.wxc.xcConfirm(result.errorMsg,
						window.wxc.xcConfirm.typeEnum.error);
			} else {
				$("#batchLeaveBillId").val(firstId);
				$("#batchLeaveBillDays").val(result.data[0].days);
				$("#batchLeaveBillContent").val(result.data[0].content);
				$("#batchLevaveBillRemark").val(result.data[0].remark);
				// 点击空白处不能关闭
				$('#batchUpdateModal').modal({
					backdrop : 'static',
					keyboard : false
				});
				$("#totalForBatchUpdate").html(batchTotal);
				$("#currForBatchUpdate").html(1);

				$("#batchUpdateModal").modal('show');
			}
		},
		error : function(result) {
			var txt = $.i18n.prop("leave_request_fail");
			window.wxc.xcConfirm(txt, window.wxc.xcConfirm.typeEnum.error);
		}
	});
}
function prev() {
	if (batchTotal == 1) {
		return;
	}
	if (batchCurr == 1) {
		return;
	}
	batchCurr = batchCurr - 1;
	var id = idsInt[batchCurr - 1];

	var l_id = $("#batchLeaveBillId").val();
	var l_days = $("#batchLeaveBillDays").val();
	var l_content = $("#batchLeaveBillContent").val();
	var l_remark = $("#batchLevaveBillRemark").val();

	updateLeaveBillForBatch(l_id, l_days, l_content, l_remark);
	$.ajax({
		url : "http://localhost:8888/simple_activiti/leave/select_leave.do",
		dataType : "json",
		data : "id=" + id,
		type : "post",
		success : function(result) {
			$("#batchLeaveBillId").val(result.data[0].id);
			$("#batchLeaveBillDays").val(result.data[0].days);
			$("#batchLeaveBillContent").val(result.data[0].content);
			$("#batchLevaveBillRemark").val(result.data[0].remark);
			$("#currForBatchUpdate").html(batchCurr);
		},
		error : function(result) {
			var txt = $.i18n.prop("leave_request_fail");
			window.wxc.xcConfirm(txt, window.wxc.xcConfirm.typeEnum.error);
		}
	});

}
function next() {
	if (batchTotal == 1) {
		return;
	}
	if (batchCurr + 1 > batchTotal) {
		return;
	}
	batchCurr = batchCurr + 1;
	var id = idsInt[batchCurr - 1];

	var l_id = $("#batchLeaveBillId").val();
	var l_days = $("#batchLeaveBillDays").val();
	var l_content = $("#batchLeaveBillContent").val();
	var l_remark = $("#batchLevaveBillRemark").val();

	// 得到上一页修改的数据
	updateLeaveBillForBatch(l_id, l_days, l_content, l_remark);

	$.ajax({
		url : "http://localhost:8888/simple_activiti/leave/select_leave.do",
		dataType : "json",
		data : "id=" + id,
		type : "post",
		success : function(result) {
			$("#batchLeaveBillId").val(result.data[0].id);
			$("#batchLeaveBillDays").val(result.data[0].days);
			$("#batchLeaveBillContent").val(result.data[0].content);
			$("#batchLevaveBillRemark").val(result.data[0].remark);
			$("#currForBatchUpdate").html(batchCurr);
		},
		error : function(result) {
			var txt = $.i18n.prop("leave_request_fail");
			window.wxc.xcConfirm(txt, window.wxc.xcConfirm.typeEnum.error);
		}
	});

}

function updateLeaveBillForBatch(id, l_days, l_content, l_remark) {
	$.ajax({
		url : "http://localhost:8888/simple_activiti/leave/update_leave.do",
		dataType : "json",
		type : "post",
		data : "id=" + id + "&days=" + l_days + "&content=" + l_content
				+ "&remark=" + l_remark,
		success : function(data) {

		},
		error : function(data) {
			var txt = $.i18n.prop("leave_request_fail");
			window.wxc.xcConfirm(txt, window.wxc.xcConfirm.typeEnum.error);
		}
	});
}

function doBatchUpdate() {
	var txt = $.i18n.prop("leave_batch_del_confim");
	window.wxc.xcConfirm(txt, window.wxc.xcConfirm.typeEnum.confirm, {
		onOk : function() {
			var l_id = $("#batchLeaveBillId").val();
			var l_days = $("#batchLeaveBillDays").val();
			var l_content = $("#batchLeaveBillContent").val();
			var l_remark = $("#batchLevaveBillRemark").val();
			// 1.如果就单独修改一条数据的话，这条数据点击批量修改的时候去后台修改
			// 2.用户点击到最后一页的时候，只是把前面的数据修改了，但是最后一天数据并没有修改（没有点击上一页的情况）
			updateLeaveBillForBatch(l_id, l_days, l_content, l_remark);

			$("#batchUpdateModal").modal('hide');
			var txt2 =  $.i18n.prop("leave_batch_del_success");
			window.wxc.xcConfirm(txt2, window.wxc.xcConfirm.typeEnum.info);

			// 重新刷新表格数据
			fillTableData();
		}
	});
}
